#pragma once 
#include <pthread.h>

// 将互斥量接口封装成面向对象的形式
namespace MutexModule
{
    class Mutex
    {
    public:
        Mutex()
        {
            int n = pthread_mutex_init(&_mutex, nullptr);
            (void)n;
        }
        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_mutex);
            (void)n;
        }

        void Lock()
        {
            int n = pthread_mutex_lock(&_mutex);
            (void)n;
        }

        void Unlock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            (void)n;
        }

        pthread_mutex_t* Get()  //  获取原生互斥量的指针
        {
            return &_mutex;
        }
    private:
        pthread_mutex_t _mutex;
    };
    
    // 采用RAII风格进行锁管理，当局部临界区代码运行完的时候，局部LockGuard类型的对象自动进行释放，调用析构函数释放锁
    class LockGuard
    {
    public:
        LockGuard(Mutex &mutex)
        : _mutex(mutex)
        {
            _mutex.Lock();
        }

        ~LockGuard()
        {
            _mutex.Unlock();
        }
    private:
        Mutex& _mutex;
    };
}